// backend/routes/authRoutes.js
const express = require('express');
const router = express.Router();
const db = require('../config/database');
const axios = require('axios'); // 需要安装: npm install axios

// 验证手机号格式（11位且以1开头）
function validatePhone(phone) {
    const phoneRegex = /^1\d{10}$/;
    return phoneRegex.test(phone);
}


// 微信登录接口 - MySQL版本（支持模拟登录）
router.post('/wechat-login', async (req, res) => {
    try {
        const { code, userInfo } = req.body;

        console.log('� 收到微信登录请求');
        console.log('� 请求体:', req.body);

        // 参数校验
        if (!code || !userInfo) {
            console.log('❌ 缺少必要参数：code 或 userInfo');
            return res.json({ success: false, message: '缺少必要参数' });
        }

        // 提取必要的用户信息
        const nickname = userInfo.nickName || '微信用户';
        const avatar = userInfo.avatarUrl || '';
        const gender = userInfo.gender || 0;
        const country = userInfo.country || '';
        const province = userInfo.province || '';
        const city = userInfo.city || '';
        const language = userInfo.language || 'zh_CN';

        console.log('👤 处理后的用户信息:', {
            nickname,
            avatar,
            gender,
            country,
            province,
            city,
            language
        });

        // 判断是否是模拟登录
        const isMockLogin = code.startsWith('mock_code_') || code === 'mock_code';
        console.log(`🔍 ${isMockLogin ? '识别到模拟登录' : '尝试真实登录'}`);

        // 使用MySQL数据库
        // 检查用户表是否存在，如果不存在则创建
        await db.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        openid VARCHAR(255) UNIQUE,
        nickname VARCHAR(255),
        avatar TEXT,
        gender TINYINT DEFAULT 0,
        country VARCHAR(50),
        province VARCHAR(50),
        city VARCHAR(50),
        language VARCHAR(20),
        phone VARCHAR(20),
        login_method VARCHAR(50) DEFAULT 'wechat',
        is_mock_user BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        last_login_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

        // 对于已经存在的 users 表，确保所需列存在，避免 Unknown column 错误
        try {
            const [cols] = await db.execute('SHOW COLUMNS FROM users');
            const has = (name) => cols.some(c => c.Field === name);

            const columnDefs = [
                { name: 'openid', sql: 'ALTER TABLE users ADD COLUMN openid VARCHAR(255) UNIQUE' },
                { name: 'nickname', sql: 'ALTER TABLE users ADD COLUMN nickname VARCHAR(255)' },
                { name: 'avatar', sql: 'ALTER TABLE users ADD COLUMN avatar TEXT' },
                { name: 'gender', sql: 'ALTER TABLE users ADD COLUMN gender TINYINT DEFAULT 0' },
                { name: 'country', sql: 'ALTER TABLE users ADD COLUMN country VARCHAR(50)' },
                { name: 'province', sql: 'ALTER TABLE users ADD COLUMN province VARCHAR(50)' },
                { name: 'city', sql: 'ALTER TABLE users ADD COLUMN city VARCHAR(50)' },
                { name: 'language', sql: 'ALTER TABLE users ADD COLUMN language VARCHAR(20)' },
                { name: 'login_method', sql: "ALTER TABLE users ADD COLUMN login_method VARCHAR(50) DEFAULT 'wechat'" },
                { name: 'is_mock_user', sql: 'ALTER TABLE users ADD COLUMN is_mock_user BOOLEAN DEFAULT FALSE' },
                { name: 'created_at', sql: 'ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP' },
                { name: 'last_login_at', sql: 'ALTER TABLE users ADD COLUMN last_login_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' }
            ];

            for (const def of columnDefs) {
                if (!has(def.name)) {
                    try {
                        await db.execute(def.sql);
                        console.log('✅ 微信登录初始化: 已为 users 表添加列', def.name);
                    } catch (e) {
                        // 如果列已存在或数据库不支持某些语法，忽略错误，避免影响登录流程
                        console.warn(`⚠️ 为 users 表添加列 ${def.name} 时出错:`, e.message);
                    }
                }
            }
        } catch (e) {
            console.warn('⚠️ 检查/修复 users 表结构失败（非致命）:', e.message);
        }

        // 生成openid
        let openid;
        if (isMockLogin) {
            // 模拟登录：生成带标识的模拟openid
            openid = `mock_openid_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            console.log('� 模拟登录 - 生成的openid:', openid);
        } else {
            // 真实登录尝试：生成模拟openid（实际应调用微信接口）
            openid = 'wx_' + Math.random().toString(36).substr(2, 9);
            console.log('🔑 生成模拟openid:', openid);
        }

        // 优化用户查找逻辑
        let userId;
        let userFound = false;

        // 1. 先尝试按昵称查找（更适合开发测试环境）
        let [existingUsers] = await db.execute(
            'SELECT * FROM users WHERE nickname = ? AND login_method = ?',
            [nickname, 'wechat']
        );

        if (existingUsers.length > 0) {
            userId = existingUsers[0].id;
            // 更新现有用户信息
            await db.execute(
                `UPDATE users SET openid = ?, nickname = ?, avatar = ?, gender = ?, country = ?, 
                 province = ?, city = ?, language = ?, is_mock_user = ?, last_login_at = CURRENT_TIMESTAMP 
                 WHERE id = ?`,
                [openid, nickname, avatar, gender, country, province, city, language, isMockLogin, userId]
            );
            console.log('� 更新现有用户信息成功，用户ID:', userId);
            userFound = true;
        } else {
            // 2. 如果昵称查找失败，尝试按openid查找
            [existingUsers] = await db.execute(
                'SELECT * FROM users WHERE openid = ?',
                [openid]
            );

            if (existingUsers.length > 0) {
                userId = existingUsers[0].id;
                // 更新用户信息
                await db.execute(
                    `UPDATE users SET nickname = ?, avatar = ?, gender = ?, country = ?, 
                     province = ?, city = ?, language = ?, is_mock_user = ?, last_login_at = CURRENT_TIMESTAMP 
                     WHERE id = ?`,
                    [nickname, avatar, gender, country, province, city, language, isMockLogin, userId]
                );
                console.log('🔄 通过openid更新用户信息成功，用户ID:', userId);
                userFound = true;
            }
        }

        // 3. 如果用户不存在，创建新用户
        if (!userFound) {
            const [result] = await db.execute(
                `INSERT INTO users (openid, nickname, avatar, gender, country, province, city, language, login_method, is_mock_user) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [openid, nickname, avatar, gender, country, province, city, language, 'wechat', isMockLogin]
            );
            userId = result.insertId;
            console.log(`✅ ${isMockLogin ? '创建新模拟用户' : '创建新用户'}成功，ID:`, userId);
        }

        // 获取完整的用户信息
        const [userData] = await db.execute(
            'SELECT * FROM users WHERE id = ?',
            [userId]
        );

        // 构造返回的用户信息
        const returnUserInfo = {
            nickname: userData[0].nickname,
            avatar: userData[0].avatar,
            gender: userData[0].gender,
            country: userData[0].country,
            province: userData[0].province,
            city: userData[0].city,
            language: userData[0].language,
            phone: userData[0].phone || '',   // 关键这一行
            isMockUser: userData[0].is_mock_user,
            createdAt: userData[0].created_at,
            lastLoginAt: userData[0].last_login_at
        };

        // 登录成功响应
        res.json({
            success: true,
            data: {
                userId: userId,
                openid: openid,
                userInfo: returnUserInfo,
                isMockLogin: isMockLogin
            },
            message: isMockLogin ? '模拟微信登录成功' : '微信登录成功'
        });

        console.log('✅ 微信登录处理完成');

    } catch (error) {
        console.error('❌ 微信登录处理失败:', error);
        res.json({
            success: false,
            message: '登录处理异常: ' + error.message
        });
    }
});

// 通过短信验证码重置密码
router.post('/reset-password-with-sms', async (req, res) => {
    const { phone, smsCode, newPassword } = req.body;

    try {
        if (!phone || !smsCode || !newPassword) {
            return res.json({ success: false, message: '手机号、验证码和新密码不能为空' });
        }

        if (!validatePhone(phone)) {
            return res.json({ success: false, message: '请输入正确的11位手机号码（以1开头）' });
        }

        const [users] = await db.query(
            'SELECT id, sms_code, sms_expires_at FROM users WHERE phone = ?',
            [phone]
        );

        if (users.length === 0) {
            return res.json({ success: false, message: '用户不存在，请先注册或获取验证码' });
        }

        const user = users[0];

        if (!user.sms_code) {
            return res.json({ success: false, message: '请先获取验证码' });
        }

        if (new Date() > new Date(user.sms_expires_at)) {
            return res.json({ success: false, message: '验证码已过期' });
        }

        const inputCode = String(smsCode).trim();
        const storedCode = String(user.sms_code).trim();

        if (inputCode !== storedCode) {
            return res.json({ success: false, message: '验证码错误' });
        }

        // 更新密码并清除验证码
        const [result] = await db.query(
            'UPDATE users SET password_hash = ?, sms_code = NULL, sms_expires_at = NULL WHERE id = ?',
            [newPassword, user.id]
        );

        if (result.affectedRows === 0) {
            return res.json({ success: false, message: '密码重置失败' });
        }

        res.json({ success: true, message: '密码重置成功' });
    } catch (error) {
        console.error('❌ 重置密码失败:', error);
        res.status(500).json({ success: false, message: '重置密码失败' });
    }
});

// 新增注册接口 - 添加到 authRoutes.js
router.post('/register-with-sms', async (req, res) => {
    const { phone, smsCode, password } = req.body;

    if (!phone || !smsCode || !password) {
        return res.json({ success: false, message: '参数不能为空' });
    }

    try {
        // 1. 验证验证码
        const [users] = await db.query(
            'SELECT id, sms_code, sms_expires_at, password_hash FROM users WHERE phone = ?',
            [phone]
        );

        if (users.length === 0) {
            return res.json({ success: false, message: '请先获取验证码' });
        }

        const user = users[0];

        // 检查验证码
        if (!user.sms_expires_at || new Date() > new Date(user.sms_expires_at)) {
            return res.json({ success: false, message: '验证码已过期' });
        }

        // 🚨 关键修复：修改验证码比较逻辑
        // 添加调试信息
        console.log(`🔍 注册验证码比较 - 输入: "${smsCode}" (${typeof smsCode}), 存储: "${user.sms_code}" (${typeof user.sms_code})`);

        // 统一转为字符串比较，并去除空格
        const inputCode = String(smsCode).trim();
        const storedCode = String(user.sms_code).trim();

        console.log(`🔍 注册验证码处理后 - 输入: "${inputCode}", 存储: "${storedCode}"`);

        if (inputCode !== storedCode) {
            console.log(`❌ 注册验证码不匹配`);
            return res.json({ success: false, message: '验证码错误' });
        }

        // 🚨 关键修改：如果是临时用户（没有密码），允许注册
        if (user.password_hash) {
            return res.json({
                success: false,
                message: '该手机号已注册，请直接登录',
                code: 'USER_ALREADY_REGISTERED'
            });
        }

        console.log(`✅ 验证码验证成功，开始注册用户ID: ${user.id}`);

        // 2. 设置密码完成注册
        const [result] = await db.query(
            'UPDATE users SET password_hash = ?, sms_code = NULL, sms_expires_at = NULL WHERE id = ?',
            [password, user.id]
        );

        if (result.affectedRows === 0) {
            return res.json({ success: false, message: '注册失败' });
        }

        console.log(`🎉 注册完成，用户ID: ${user.id}`);

        res.json({
            success: true,
            message: '注册成功',
            data: {
                userId: user.id
            }
        });

    } catch (error) {
        console.error('❌ 注册失败:', error);
        res.status(500).json({ success: false, message: '注册失败' });
    }
});

// 发送验证码接口 - 修复版
router.post('/send-sms', async (req, res) => {
    console.log('=== 🎯 发送验证码调试 ===');
    const { phone } = req.body;
    const smsCode = Math.floor(100000 + Math.random() * 900000).toString();

    console.log(`📱 手机号: ${phone}`);
    console.log(`🔢 生成的验证码: ${smsCode}`);

    try {
        // 验证手机号格式
        if (!phone || !validatePhone(phone)) {
            console.log('❌ 手机号格式错误');
            return res.status(400).json({
                success: false,
                message: '请输入正确的11位手机号码（以1开头）'
            });
        }
        // 1. 检查用户是否存在
        const [users] = await db.query(
            'SELECT id FROM users WHERE phone = ?',
            [phone]
        );

        if (users.length === 0) {
            console.log('❌ 用户不存在，创建临时用户');
            // 创建临时用户记录
            const [insertResult] = await db.query(
                'INSERT INTO users (phone, sms_code, sms_expires_at, created_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 10 MINUTE), NOW())',
                [phone, smsCode]
            );
            console.log('✅ 创建临时用户成功，ID:', insertResult.insertId);
        } else {
            // 2. 更新现有用户的验证码
            console.log('✅ 用户存在，更新验证码');
            const [updateResult] = await db.query(
                'UPDATE users SET sms_code = ?, sms_expires_at = DATE_ADD(NOW(), INTERVAL 10 MINUTE) WHERE phone = ?',
                [smsCode, phone]
            );
            console.log('📊 更新结果 - 受影响行数:', updateResult.affectedRows);
        }

        // 3. 立即验证更新是否成功
        const [verify] = await db.query(
            'SELECT id, phone, sms_code, sms_expires_at FROM users WHERE phone = ?',
            [phone]
        );

        console.log('🔍 数据库验证结果:', verify[0]);

        if (verify[0] && verify[0].sms_code === smsCode) {
            console.log('🎉 验证码保存成功！');
            res.json({
                success: true,
                message: '验证码发送成功',
                data: {
                    smsCode: smsCode, // 开发环境返回，生产环境去掉
                    debug: `验证码已保存到数据库: ${smsCode}`
                }
            });
        } else {
            console.log('❌ 验证码保存失败！');
            res.json({
                success: false,
                message: '验证码保存失败',
                debug: {
                    expected: smsCode,
                    actual: verify[0]?.sms_code
                }
            });
        }

    } catch (error) {
        console.error('💥 发送验证码错误:', error);
        res.status(500).json({
            success: false,
            message: '发送验证码失败',
            error: error.message
        });
    }
});

// 绑定手机号给微信用户（使用短信验证码校验）
router.post('/bind-phone-wechat', async (req, res) => {
    const { userId, phone, smsCode } = req.body;

    try {
        if (!userId || !phone || !smsCode) {
            return res.json({ success: false, message: 'userId、手机号和验证码不能为空' });
        }

        if (!validatePhone(phone)) {
            return res.json({ success: false, message: '请输入正确的11位手机号码（以1开头）' });
        }

        // 1. 先根据手机号查找验证码记录
        const [smsUsers] = await db.query(
            'SELECT id, sms_code, sms_expires_at FROM users WHERE phone = ?',
            [phone]
        );

        if (smsUsers.length === 0) {
            return res.json({ success: false, message: '请先获取验证码' });
        }

        const smsUser = smsUsers[0];

        if (!smsUser.sms_code) {
            return res.json({ success: false, message: '请先获取验证码' });
        }

        if (new Date() > new Date(smsUser.sms_expires_at)) {
            return res.json({ success: false, message: '验证码已过期' });
        }

        const inputCode = String(smsCode).trim();
        const storedCode = String(smsUser.sms_code).trim();

        if (inputCode !== storedCode) {
            return res.json({ success: false, message: '验证码错误' });
        }

        // 2. 验证通过后，处理账号合并 / 绑定逻辑
        // 目标：一个手机号只对应一个账号，如果手机号已存在于其他账号，则把当前微信账号合并到该手机号账号
        let targetUserId = userId;

        // 查询当前手机号对应的用户（如果有的话）
        const [phoneUsers] = await db.query(
            'SELECT * FROM users WHERE phone = ?',
            [phone]
        );

        if (phoneUsers.length > 0 && phoneUsers[0].id !== userId) {
            // 情况 A：手机号已经被另一个账号使用（典型场景：先用手机号注册/登录过）
            const phoneUser = phoneUsers[0];

            // 读取当前微信登录用户的信息
            const [wechatRows] = await db.query(
                'SELECT * FROM users WHERE id = ?',
                [userId]
            );

            if (wechatRows.length === 0) {
                return res.json({ success: false, message: '当前微信用户不存在' });
            }

            const w = wechatRows[0];

            // 2.1 先释放当前微信用户记录上的 openid，避免唯一索引冲突
            if (w.openid) {
                await db.query('UPDATE users SET openid = NULL WHERE id = ?', [userId]);
            }

            // 2.2 把微信相关信息合并到已有的手机号账号上
            await db.query(
                `UPDATE users SET openid = ?, nickname = ?, avatar = ?, gender = ?, country = ?, province = ?, city = ?, language = ?, login_method = 'wechat', is_mock_user = ? WHERE id = ?`,
                [
                    w.openid,
                    w.nickname,
                    w.avatar,
                    w.gender,
                    w.country,
                    w.province,
                    w.city,
                    w.language,
                    w.is_mock_user,
                    phoneUser.id
                ]
            );

            // 2.3 将目标用户设为「手机号账号」，后续返回它的 userId
            targetUserId = phoneUser.id;
        } else {
            // 情况 B：手机号目前未被其他账号使用，直接绑定到当前微信用户
            const [updateResult] = await db.query(
                'UPDATE users SET phone = ? WHERE id = ?',
                [phone, userId]
            );

            if (updateResult.affectedRows === 0) {
                return res.json({ success: false, message: '绑定失败，用户不存在' });
            }
        }

        // 3. 清除该手机号上的验证码，避免重复使用
        await db.query(
            'UPDATE users SET sms_code = NULL, sms_expires_at = NULL WHERE phone = ?',
            [phone]
        );

        // 4. 返回更新后的用户信息（始终以 targetUserId 为准，实现账号合并）
        const [userRows] = await db.query(
            'SELECT id, nickname, avatar, gender, country, province, city, language, phone FROM users WHERE id = ?',
            [targetUserId]
        );

        if (userRows.length === 0) {
            return res.json({ success: false, message: '用户不存在' });
        }

        const user = userRows[0];

        res.json({
            success: true,
            message: '手机号绑定成功',
            data: {
                userId: user.id,
                userInfo: {
                    nickname: user.nickname,
                    avatar: user.avatar,
                    gender: user.gender,
                    country: user.country,
                    province: user.province,
                    city: user.city,
                    language: user.language,
                    phone: user.phone
                }
            }
        });
    } catch (error) {
        console.error('❌ 绑定手机号失败:', error);
        res.status(500).json({ success: false, message: '绑定手机号失败' });
    }
});

// 直接测试接口 - 增强版
router.post('/direct-test', async (req, res) => {
    console.log('=== 🔥 直接SQL测试 ===');

    try {
        const testPhone = "13058325914"; // 使用你的测试手机号

        // 测试1：查询当前状态
        console.log('1. 查询当前状态...');
        const [current] = await db.execute(
            'SELECT id, phone, sms_code, sms_expires_at FROM users WHERE phone = ?',
            [testPhone]
        );
        console.log('🔍 当前状态:', current[0]);

        // 测试2：生成并保存新验证码
        const testCode = Math.floor(100000 + Math.random() * 900000).toString();
        console.log(`2. 生成测试验证码: ${testCode}`);

        const [updateResult] = await db.execute(
            'UPDATE users SET sms_code = ?, sms_expires_at = DATE_ADD(NOW(), INTERVAL 10 MINUTE) WHERE phone = ?',
            [testCode, testPhone]
        );
        console.log('📊 更新结果:', updateResult);

        // 测试3：立即验证
        console.log('3. 验证更新...');
        const [verify] = await db.execute(
            'SELECT id, phone, sms_code, sms_expires_at FROM users WHERE phone = ?',
            [testPhone]
        );
        console.log('🔍 验证结果:', verify[0]);

        res.json({
            success: true,
            data: {
                before: current[0],
                update: updateResult,
                after: verify[0],
                generatedCode: testCode
            }
        });

    } catch (error) {
        console.error('💥 直接测试错误:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// 直接测试SQL执行
router.post('/direct-test', async (req, res) => {
    console.log('=== 🔥 直接SQL测试 ===');

    try {
        const connection = await db.getConnection();

        // 测试1：直接执行完全相同的SQL
        console.log('1. 执行完全相同的UPDATE...');
        const [result1] = await connection.execute(
            'UPDATE users SET sms_code = "111111" WHERE phone = "13058325914"'
        );
        console.log('📊 直接UPDATE结果:', result1);

        // 测试2：使用参数化查询
        console.log('2. 执行参数化UPDATE...');
        const [result2] = await connection.execute(
            'UPDATE users SET sms_code = ? WHERE phone = ?',
            ['222222', '13058325914']
        );
        console.log('📊 参数化UPDATE结果:', result2);

        // 立即验证
        console.log('3. 立即验证...');
        const [verify] = await connection.execute(
            'SELECT phone, sms_code FROM users WHERE phone = "13058325914"'
        );
        console.log('🔍 验证结果:', verify[0]);

        connection.release();

        res.json({
            directUpdate: result1,
            paramUpdate: result2,
            verify: verify[0]
        });

    } catch (error) {
        console.error('💥 直接测试错误:', error);
        res.json({ error: error.message });
    }
});
// 密码登录接口
router.post('/login-with-password', async (req, res) => {
    const { phone, password } = req.body;

    // 验证手机号格式
    if (!phone || !validatePhone(phone)) {
        return res.json({ success: false, message: '请输入正确的11位手机号码（以1开头）' });
    }

    if (!password) {
        return res.json({ success: false, message: '密码不能为空' });
    }

    try {
        // 查找用户
        const [users] = await db.query(
            'SELECT id, password_hash, nickname, avatar_url FROM users WHERE phone = ?',
            [phone]
        );

        if (users.length === 0) {
            return res.json({ success: false, message: '手机号未注册' });
        }

        const user = users[0];

        if (!user.password_hash) {
            return res.json({ success: false, message: '请先设置密码' });
        }

        // 验证密码（生产环境应该用bcrypt.compare）
        if (user.password_hash !== password) {
            return res.json({ success: false, message: '密码错误' });
        }

        console.log(`✅ 密码登录成功，用户ID: ${user.id}`);

        res.json({
            success: true,
            message: '登录成功',
            data: {
                userId: user.id,
                userInfo: {
                    nickname: user.nickname,
                    avatarUrl: user.avatar_url
                }
            }
        });

    } catch (error) {
        console.error('❌ 密码登录失败:', error);
        res.status(500).json({ success: false, message: '登录失败' });
    }
});

// 设置密码接口
router.post('/set-password', async (req, res) => {
    const { userId, password } = req.body;

    if (!userId || !password) {
        return res.json({ success: false, message: '参数不能为空' });
    }

    try {
        // 更新密码（生产环境应该用bcrypt加密）
        const [result] = await db.query(
            'UPDATE users SET password_hash = ? WHERE id = ?',
            [password, userId]
        );

        if (result.affectedRows === 0) {
            return res.json({ success: false, message: '用户不存在' });
        }

        console.log(`✅ 密码设置成功，用户ID: ${userId}`);

        res.json({
            success: true,
            message: '密码设置成功'
        });

    } catch (error) {
        console.error('❌ 设置密码失败:', error);
        res.status(500).json({ success: false, message: '设置密码失败' });
    }
});


module.exports = router;